<template>
  
  <div class="doctor-appointment-container">
    <!-- 头部信息 -->
    <div class="header">
      <h1>我的接诊管理</h1>
      <p class="subtitle">查看和管理患者接诊记录</p>
    </div>

    <!-- 医生信息卡片 -->
    <div class="doctor-card">
      <div class="avatar-container">
        <img :src="doctorInfo.img" alt="医生头像" class="doctor-avatar">
      </div>
      <div class="doctor-meta">
        <h2>{{ doctorInfo.doc_name }} <span class="title-badge">{{ doctorInfo.doc_title }}</span></h2>
        <p class="department">{{ getDepartmentName(doctorInfo.depart_id1) }} - {{ getDepartmentName(doctorInfo.depart_id2) }}</p>
        <div class="stats-row">
          <div class="stat-item">
            <div class="stat-value">{{ totalAppointments }}</div>
            <div class="stat-label">本周接诊</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ todayAppointments.length }}</div>
            <div class="stat-label">今日接诊</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ differentPatients }}</div>
            <div class="stat-label">不同患者</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 周导航和日期选择 -->
    <div class="week-navigation-container">
      <div class="week-navigation">
        <button class="nav-button" @click="changeWeek(-1)">
          <i class="icon-arrow-left"></i> 上周
        </button>
        <span class="current-week">{{ currentWeekRange }}</span>
        <button class="nav-button" @click="changeWeek(1)">
          下周 <i class="icon-arrow-right"></i>
        </button>
      </div>
      
      <div class="day-tabs">
        <button 
          v-for="day in weekDays" 
          :key="day.dateString"
          class="day-tab"
          :class="{ active: activeDay === day.dateString, today: isToday(day.dateString) }"
          @click="selectDay(day.dateString)"
        >
          <div class="weekday">{{ day.weekday }}</div>
          <div class="date">{{ day.date.split('月')[1] }}</div>
          <div v-if="dayAppointments[day.dateString]?.length > 0" class="appointment-badge">
            {{ dayAppointments[day.dateString]?.length }}
          </div>
        </button>
      </div>
    </div>

    <!-- 接诊列表 -->
    <div class="appointment-list-container">
      <div v-if="loading" class="loading-overlay">
        <div class="spinner"></div>
      </div>
      
      <div v-if="activeDayAppointments.length === 0 && !loading" class="empty-state">
        <el-empty description="当日无接诊记录" :image-size="100" />
      </div>
      
      <div v-else class="appointment-list">
        <div 
          v-for="appointment in activeDayAppointments" 
          :key="appointment.id"
          class="appointment-card"
          :class="{ 'diagnosed': appointment.diagnosisStatus }"
        >
          <div class="appointment-header">
            <div class="patient-info">
              <div class="patient-name">{{ appointment.name }}
                <span v-if="appointment.diagnosisStatus" class="status-badge">已诊断</span>
                <span v-else class="status-badge pending">待诊断</span>
              </div>
              <div class="patient-meta">
                <span class="meta-item">
                  <i class="icon-phone"></i> {{ appointment.telephone }}
                </span>
                <span class="meta-item">
                  <i class="icon-clock"></i> {{ formatTime(appointment.createTime) }}
                </span>
              </div>
            </div>
            <div class="appointment-time">
              {{ getTimePeriod(appointment.info) }}
            </div>
          </div>
          <div class="appointment-notes">
            <div class="notes-label">备注信息:</div>
            <div class="notes-content">{{ getNotes(appointment.info) || '无备注信息' }}</div>
          </div>
          <div class="appointment-actions">
            <el-button 
              size="small" 
              type="primary" 
              @click="startDiagnosis(appointment)"
              :disabled="isPastDate(appointment.day) || appointment.diagnosisStatus"
            >
              {{ appointment.diagnosisStatus ? '已完成诊断' : '开始诊断' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计图表 -->
    <div class="stats-container">
      <h3 class="stats-title">本周接诊统计</h3>
      <div class="chart-container">
        <div class="chart">
          <div 
            v-for="day in weekDays" 
            :key="day.dateString"
            class="chart-bar-container"
          >
            <div class="chart-bar-label">{{ day.weekday }}</div>
            <div class="chart-bar-background">
              <div 
                class="chart-bar" 
                :style="{ height: getBarHeight(day.dateString) }"
              ></div>
            </div>
            <div class="chart-bar-value">
              {{ dayAppointments[day.dateString]?.length || 0 }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { ElEmpty, ElButton, ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import weekOfYear from 'dayjs/plugin/weekOfYear'
import isoWeek from 'dayjs/plugin/isoWeek'
import head from '@/components/icons/head.vue'

// 扩展 dayjs 插件
dayjs.extend(weekOfYear)
dayjs.extend(isoWeek)

const userStore = useUserStore()
const doctorInfo = ref({})
const appointments = ref([])
const loading = ref(true)
const currentWeekOffset = ref(0)
const activeDay = ref('')

// 模拟科室数据
const departments = {
  1: "内科",
  2: "外科",
  3: "妇科",
  4: "儿科",
  5: "传染病",
  6: "五官科",
  7: "中医科",
  8: "检验科",
  9: "放射科",
  10: "超声科",
  11: "胃镜科",
  12: "药剂科",
  13: "行政科室",
  14: "神经内科",
  15: "急诊科",
  16: "康复科",
  17: "心理科",
  18: "营养科",
  19: "病理科",
  20: "心外科",
  28: "妇产科",
  38: "发烧发热",
  39: "皮肤外科",
  51: "传染预防科",
  52: "心内科",
  53: "骨外科",
  54: "CT 门诊",
  61: "耳鼻喉",
  100: "呼吸内科",
  101: "消化内科",
  102: "神经外科",
  103: "妇科肿瘤",
  104: "生殖医学科",
  105: "新生儿科",
  106: "儿童保健科",
  107: "感染性疾病科",
  108: "结核病科",
  109: "眼科",
  110: "口腔科",
  111: "针灸科",
  112: "推拿科",
  113: "中医康复科",
  114: "生化检验",
  115: "免疫检验",
  116: "微生物检验",
  117: "MRI 室",
  118: "X 光室",
  119: "心脏超声",
  120: "腹部超声",
  121: "妇产超声",
  122: "普通胃镜",
  123: "无痛胃镜",
  124: "肠镜检查",
  125: "门诊药房",
  126: "住院药房",
  127: "临床药学",
  128: "人事科",
  129: "财务科",
  130: "医务科",
  131: "急诊内科",
  132: "急诊外科",
  133: "急诊儿科",
  134: "物理治疗科",
  135: "作业治疗科",
  136: "言语治疗科",
  137: "心理咨询",
  138: "心理治疗",
  139: "儿童心理科",
  140: "临床营养",
  141: "膳食管理",
  142: "营养评估",
  143: "组织病理",
  144: "细胞病理",
  145: "分子病理"
}

const getDepartmentName = (id) => {
  return departments[id] || `科室${id}`
}

// 获取当前周的日期范围
const getCurrentWeekDays = (offset = 0) => {
  const now = new Date()
  now.setDate(now.getDate() + offset * 7)
  const currentDay = now.getDay()
  const monday = new Date(now)
  
  // 设置为本周一
  monday.setDate(monday.getDate() - (currentDay === 0 ? 6 : currentDay - 1))
  
  const weekDays = []
  const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  
  for (let i = 0; i < 7; i++) {
    const day = new Date(monday)
    day.setDate(monday.getDate() + i)
    
    const formattedDate = `${day.getMonth() + 1}月${day.getDate()}日`
    const dateString = `${day.getFullYear()}-${(day.getMonth() + 1).toString().padStart(2, '0')}-${day.getDate().toString().padStart(2, '0')}`
    
    weekDays.push({
      date: formattedDate,
      weekday: weekdays[i],
      dateString: dateString,
      dateObj: new Date(day)
    })
  }
  
  return weekDays
}

const weekDays = ref(getCurrentWeekDays())

// 计算当前周的范围显示文本
const currentWeekRange = computed(() => {
  if (weekDays.value.length === 0) return ''
  const firstDay = weekDays.value[0].dateObj
  const lastDay = weekDays.value[6].dateObj
  return `${firstDay.getMonth() + 1}月${firstDay.getDate()}日 - ${lastDay.getMonth() + 1}月${lastDay.getDate()}日`
})

// 检查是否是今天
const isToday = (dateStr) => {
  const today = new Date()
  const date = new Date(dateStr)
  return date.getFullYear() === today.getFullYear() && 
         date.getMonth() === today.getMonth() && 
         date.getDate() === today.getDate()
}

// 检查是否是过去日期（不包括今天）
const isPastDate = (dateStr) => {
  const today = dayjs().format('YYYY-MM-DD')
  return dateStr < today
}

// 按日期分组的接诊记录
const dayAppointments = computed(() => {
  const result = {}
  weekDays.value.forEach(day => {
    result[day.dateString] = appointments.value.filter(
      app => app.day === day.dateString
    )
  })
  return result
})

// 当前选中日的接诊记录
const activeDayAppointments = computed(() => {
  return dayAppointments.value[activeDay.value] || []
})

// 统计信息
const totalAppointments = computed(() => {
  return Object.values(dayAppointments.value).reduce(
    (sum, dayApps) => sum + dayApps.length, 0
  )
})

const todayAppointments = computed(() => {
  const today = dayjs().format('YYYY-MM-DD')
  return appointments.value.filter(app => app.day === today)
})

const differentPatients = computed(() => {
  const patientIds = new Set()
  appointments.value.forEach(app => patientIds.add(app.patientId))
  return patientIds.size
})

// 获取医生信息
const fetchDoctorInfo = async () => {
  try {
    const response = await axios.get(
      `http://localhost:8080/hospital5/doctor/findByUserName?user_name=${userStore.userInfo.userName}`
    )
    if (response.data && response.data.length > 0) {
      doctorInfo.value = response.data[0]
      return response.data[0].doc_id
    }
    return null
  } catch (error) {
    console.error('获取医生信息失败:', error)
    ElMessage.error('获取医生信息失败')
    return null
  }
}

// 获取接诊记录
const fetchAppointments = async (docId) => {
  try {
    loading.value = true
    const response = await axios.get(
      `http://localhost:8080/hospital5/patientDoctor/findByDocId?docId=${docId}`
    )
    appointments.value = response.data || []
    
    // 设置默认选中日期为今天或第一个有接诊记录的日期
    const today = dayjs().format('YYYY-MM-DD')
    const hasTodayAppointments = appointments.value.some(app => app.day === today)
    activeDay.value = hasTodayAppointments ? today : 
      (appointments.value[0]?.day || weekDays.value[0].dateString)
  } catch (error) {
    console.error('获取接诊记录失败:', error)
    ElMessage.error('获取接诊记录失败')
  } finally {
    loading.value = false
  }
}

// 切换周
const changeWeek = (offset) => {
  currentWeekOffset.value += offset
  weekDays.value = getCurrentWeekDays(currentWeekOffset.value)
  
  // 尝试保持选择的日期在新的一周中
  const newWeekDates = weekDays.value.map(day => day.dateString)
  if (!newWeekDates.includes(activeDay.value)) {
    activeDay.value = newWeekDates[0]
  }
}

// 选择日期
const selectDay = (dateString) => {
  activeDay.value = dateString
}

// 格式化时间
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('HH:mm')
}

// 从info中提取时间段
const getTimePeriod = (info) => {
  const match = info.match(/上午|下午/)
  return match ? match[0] : '未知时间段'
}

// 从info中提取备注
const getNotes = (info) => {
  const parts = info.split('-')
  return parts.length > 1 ? parts[1].trim() : ''
}

// 计算柱状图高度
const getBarHeight = (dateString) => {
  const count = dayAppointments.value[dateString]?.length || 0
  const maxCount = Math.max(1, ...Object.values(dayAppointments.value).map(day => day.length))
  return `${(count / maxCount) * 100}%`
}

// 开始诊断
const startDiagnosis = async (appointment) => {
  try {
    if (isPastDate(appointment.day)) {
      ElMessage.warning('不能对过去的日期进行诊断操作')
      return
    }
    
    if (appointment.diagnosisStatus) {
      ElMessage.info('该患者已完成诊断')
      return
    }
    
    // 调用接口更新诊断状态
    await axios.post(
      `http://localhost:8080/hospital5/patientDoctor/markAsDiagnosed?id=${appointment.id}`
    )
    
    // 更新本地数据
    const index = appointments.value.findIndex(a => a.id === appointment.id)
    if (index !== -1) {
      appointments.value[index].diagnosisStatus = true
    }
    
    ElMessage.success(`已标记 ${appointment.name} 为已诊断`)
  } catch (error) {
    console.error('更新诊断状态失败:', error)
    ElMessage.error('更新诊断状态失败')
  }
}

// 初始化
onMounted(async () => {
  const docId = await fetchDoctorInfo()
  if (docId) {
    await fetchAppointments(docId)
  }
})
</script>

<style scoped>
.doctor-appointment-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #333;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  font-size: 2.2rem;
  color: #2c3e50;
  margin-bottom: 5px;
}

.subtitle {
  font-size: 1rem;
  color: #7f8c8d;
}

/* 医生卡片样式 */
.doctor-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  display: flex;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.avatar-container {
  margin-right: 25px;
}

.doctor-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.doctor-meta {
  flex: 1;
}

.doctor-meta h2 {
  font-size: 1.5rem;
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.title-badge {
  display: inline-block;
  background-color: #3498db;
  color: white;
  font-size: 0.9rem;
  padding: 3px 10px;
  border-radius: 15px;
  margin-left: 10px;
  vertical-align: middle;
}

.department {
  color: #7f8c8d;
  margin: 0 0 15px 0;
  font-size: 1rem;
}

.stats-row {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.stat-item {
  background-color: white;
  padding: 10px 15px;
  border-radius: 8px;
  min-width: 80px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stat-value {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 3px;
}

.stat-label {
  font-size: 0.8rem;
  color: #7f8c8d;
}

/* 周导航样式 */
.week-navigation-container {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.week-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.nav-button {
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  padding: 8px 15px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.2s;
}

.nav-button:hover {
  background-color: #e9ecef;
  border-color: #adb5bd;
}

.icon-arrow-left, .icon-arrow-right {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #555;
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 18l-6-6 6-6'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
}

.icon-arrow-right {
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 18l6-6-6-6'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
}

.current-week {
  font-weight: bold;
  color: #2c3e50;
}

.day-tabs {
  display: flex;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f8f9fa;
}

.day-tab {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
  border: none;
  background: none;
}

.day-tab:hover {
  background-color: #e9ecef;
}

.day-tab.active {
  background-color: #3498db;
  color: white;
}

.day-tab.today {
  font-weight: bold;
}

.day-tab.today:not(.active) {
  color: #e74c3c;
}

.weekday {
  font-size: 0.9rem;
  margin-bottom: 3px;
}

.date {
  font-size: 1.1rem;
}

.appointment-badge {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 18px;
  height: 18px;
  background-color: #e74c3c;
  color: white;
  border-radius: 50%;
  font-size: 0.7rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.day-tab.active .appointment-badge {
  background-color: white;
  color: #e74c3c;
}

/* 接诊列表样式 */
.appointment-list-container {
  position: relative;
  min-height: 300px;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 30px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.appointment-list {
  display: grid;
  gap: 15px;
}

.appointment-card {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  transition: all 0.2s;
  border-left: 4px solid #3498db;
}

.appointment-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.appointment-card.diagnosed {
  background-color: #f0f9eb;
  border-left-color: #67c23a;
}

.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.patient-info {
  flex: 1;
}

.patient-name {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-badge {
  font-size: 0.75rem;
  padding: 2px 8px;
  border-radius: 10px;
  background-color: #67c23a;
  color: white;
}

.status-badge.pending {
  background-color: #e6a23c;
}

.patient-meta {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #7f8c8d;
}

.meta-item {
  display: flex;
  align-items: center;
}

.icon-phone, .icon-clock {
  display: inline-block;
  width: 14px;
  height: 14px;
  background-color: currentColor;
  margin-right: 5px;
}

.icon-phone {
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z'%3E%3C/path%3E%3C/svg%3E") no-repeat center;
}

.icon-clock {
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpolyline points='12 6 12 12 16 14'%3E%3C/polyline%3E%3C/svg%3E") no-repeat center;
}

.appointment-time {
  background-color: #e3f2fd;
  color: #1976d2;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 0.9rem;
  font-weight: bold;
}

.appointment-notes {
  margin-bottom: 10px;
  padding: 10px;
  background-color: white;
  border-radius: 6px;
}

.notes-label {
  font-size: 0.9rem;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.notes-content {
  font-size: 0.95rem;
}

.appointment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 统计图表样式 */
.stats-container {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stats-title {
  margin-top: 0;
  margin-bottom: 20px;
  color: #2c3e50;
}

.chart-container {
  overflow-x: auto;
}

.chart {
  display: flex;
  height: 200px;
  align-items: flex-end;
  gap: 20px;
  min-width: 100%;
  padding: 20px 0;
}

.chart-bar-container {
  flex: 1;
  min-width: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.chart-bar-label {
  margin-bottom: 10px;
  font-size: 0.9rem;
}

.chart-bar-background {
  width: 30px;
  height: 150px;
  background-color: #f0f0f0;
  border-radius: 4px;
  position: relative;
}

.chart-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #3498db;
  border-radius: 4px;
  transition: height 0.5s ease;
}

.chart-bar-value {
  margin-top: 5px;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .doctor-card {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .avatar-container {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .stats-row {
    justify-content: center;
  }
  
  .day-tabs {
    flex-wrap: wrap;
  }
  
  .day-tab {
    min-width: calc(100% / 4);
  }
  
  .appointment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .appointment-time {
    align-self: flex-start;
  }
  
  .chart {
    gap: 10px;
  }
  
  .chart-bar-container {
    min-width: 40px;
  }
  
  .chart-bar-background {
    width: 20px;
  }
}
</style>